﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Help_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        // Get the uids of the selected friends as a List<String>
        Int32[] selectedFriendIndicies = this.lbFriends.GetSelectedIndices();
        List<String> friends = new List<String>(selectedFriendIndicies.Length);
        Dictionary<String, String> names = new Dictionary<String, String>();
        foreach (Int32 index in selectedFriendIndicies) 
        { 
            friends.Add(this.lbFriends.Items[index].Value);
            names.Add(this.lbFriends.Items[index].Value, this.lbFriends.Items[index].Text);
        }
        String prankId = this.ddlPranks.SelectedItem.Value;
        // Publish the mini feed story
        Facebook.Service.FacebookService svc = this.Master.ParentApp.Service;
        Facebook.Service.FeedStoryTemplate template = new Facebook.Service.FeedStoryTemplate(
            Resources.Strings.FeedStoryTemplateTitle, this.ddlPranks.SelectedItem.Text + Resources.Strings.FeedStoryTemplateBody);
        Facebook.Service.FeedStory story = new Facebook.Service.FeedStory(template, svc.UserID, friends);
        if (!Master.InTestMode) svc.Feed.PublishMiniFeedStory(story);
        // Notify each friends
        foreach (String uid in friends)
        {
            String notification = "says '" + this.ddlPranks.SelectedItem.Text.Replace("{target}", names[uid]) + "'";
            if (!Master.InTestMode) svc.Notifications.SendNotification(friends, notification, null);
        }
        // Record the prank in the database
        DBDataContext db = new DBDataContext();
        db.Log = new DebuggerWriter();
        sent_prank sp = 
            new sent_prank
            {
                prank_id = Int32.Parse(prankId),
                sender_id = Int64.Parse(svc.UserID),
                sent_on = DateTime.Now
            };
        foreach (String friend in friends)
        {
            sent_prank_recipient spr = new sent_prank_recipient { recipient_id = Int64.Parse(friend) };
            sp.sent_prank_recipients.Add(spr);
        }
        db.sent_pranks.InsertOnSubmit(sp);
        db.SubmitChanges();
        //db.SubmitChanges();
        // Switch the page elements
        this.pnlBefore.Visible = false;
        this.pnlAfter.Visible = true;
        // Update the status
        this.lblPrankNo.Text = prankId;
        this.lblTargetCount.Text = friends.Count.ToString();
    }
}
